package per.turtle.common.security.feign;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import per.turtle.common.core.constant.CacheConstants;
import per.turtle.common.core.utils.ServletUtils;
import per.turtle.common.redis.service.RedisService;
import per.turtle.common.security.aspect.OnlyInterServiceAspect;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * feign 请求拦截器
 *
 * @author turtle
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Autowired
    private RedisService redisService;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest httpServletRequest = ServletUtils.getRequest();
        if (BeanUtil.isNotEmpty(httpServletRequest)) {
            assert httpServletRequest != null;
            Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);
            // 传递用户信息请求头，防止丢失
            String userId = headers.get(CacheConstants.DETAILS_USER_ID);
            if (StrUtil.isNotEmpty(userId)) {
                requestTemplate.header(CacheConstants.DETAILS_USER_ID, userId);
            }
            String userName = headers.get(CacheConstants.DETAILS_USERNAME);
            if (StrUtil.isNotEmpty(userName)) {
                requestTemplate.header(CacheConstants.DETAILS_USERNAME, userName);
            }
            String authentication = headers.get(CacheConstants.AUTHORIZATION_HEADER);
            if (StrUtil.isNotEmpty(authentication)) {
                requestTemplate.header(CacheConstants.AUTHORIZATION_HEADER, authentication);
            }
            // 用于只允许服务间调用的验证
            String keyId = IdUtil.fastUUID();
            redisService.setCacheObject(OnlyInterServiceAspect.CACHE_KEY + keyId, OnlyInterServiceAspect.getCheckStr(keyId), 30L, TimeUnit.SECONDS);
            requestTemplate.header(OnlyInterServiceAspect.CACHE_KEY, keyId);

            // 配置客户端IP
            requestTemplate.header("X-Forwarded-For", ServletUtil.getClientIP(httpServletRequest));

        }
    }

}